package org.yray.tika;


import lombok.extern.slf4j.Slf4j;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.ocr.TesseractOCRConfig;
import org.apache.tika.parser.ocr.TesseractOCRParser;
import org.apache.tika.sax.BodyContentHandler;
import org.junit.Test;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
public class Tesseract {
    @Test
    public void testCode() throws IOException, SAXException, TikaException, InterruptedException {

        TesseractOCRParser parser = new TesseractOCRParser();


        TesseractOCRConfig config = new TesseractOCRConfig();
        // 设置简体中文训练集
        config.setLanguage("chi_sim");
        ParseContext context = new ParseContext();
        context.set(TesseractOCRConfig.class, config);
        context.set(TesseractOCRParser.class, parser);
        BodyContentHandler handler = new BodyContentHandler();
        File file = new File("D:/test/tika");
        parser.setTesseractPath("C:\\Program Files\\Tesseract-OCR");
        parser.setTessdataPath("C:\\Program Files\\Tesseract-OCR\\tessdata");
        parser.initialize(null);

        if (file.exists()) {
            File[] files= file.listFiles();
            for (File name:files)
            {
                Metadata metadata = new Metadata();
                try (InputStream stream = new FileInputStream(name)) {
                    parser.parse(stream, handler, metadata, context);
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
                System.out.println(handler.toString());
            }
        }

    }

}
